<!-- Google登录SDK -->
<script src="https://accounts.google.com/gsi/client" async defer></script>

<!-- 认证状态卡片 -->
<div class="row mb-5">
    <div class="col-12">
        <div class="feature-card">
            <div class="card-body">
                <div class="d-flex align-items-center justify-content-between mb-4">
                    <div class="d-flex align-items-center">
                        <div class="bg-gradient rounded-circle d-inline-flex align-items-center justify-content-center me-3" style="width: 60px; height: 60px; background: var(--primary-gradient);">
                            <i class="fas fa-user-circle text-white fa-2x"></i>
                        </div>
                        <div>
                            <h5 class="card-title mb-1 fw-bold">认证状态中心</h5>
                            <p class="text-muted mb-0">实时显示当前登录状态和用户信息</p>
                        </div>
                    </div>
                    <div>
                        <span id="auth-status" class="status-badge status-stopped">
                            <i class="fas fa-circle me-2"></i>未登录
                        </span>
                    </div>
                </div>
                
                <div id="user-info" class="d-none">
                    <div class="bg-light rounded-4 p-4 mb-4">
                        <div class="row align-items-center">
                            <div class="col-md-8">
                                <h6 class="fw-bold text-success mb-3">
                                    <i class="fas fa-check-circle me-2"></i>用户已登录
                                </h6>
                                <div id="user-details"></div>
                            </div>
                            <div class="col-md-4 text-center">
                                <button class="btn btn-danger btn-custom" onclick="logout()">
                                    <i class="fas fa-sign-out-alt me-2"></i>安全登出
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 登录方式选择 -->
<div class="row mb-5" id="login-forms">
    <div class="col-12 mb-4">
        <div class="text-center">
            <h3 class="fw-bold">选择登录方式</h3>
            <p class="text-muted">请选择您偏好的认证方式进行登录</p>
        </div>
    </div>
    
    <!-- Google OAuth登录 -->
    <div class="col-lg-6 mb-4">
        <div class="feature-card h-100">
            <div class="card-body">
                <div class="text-center mb-4">
                    <div class="bg-gradient rounded-circle d-inline-flex align-items-center justify-content-center mb-3" style="width: 80px; height: 80px; background: linear-gradient(135deg, #ea4335, #fbbc05);">
                        <i class="fab fa-google fa-2x text-white"></i>
                    </div>
                    <h5 class="card-title fw-bold">Google 快速登录</h5>
                    <p class="text-muted">使用您的Google账户安全便捷地登录</p>
                </div>
                
                <div id="google-signin-button" class="d-flex justify-content-center mb-4"></div>
                
                <div class="bg-light rounded-3 p-3">
                    <div class="d-flex align-items-start">
                        <i class="fas fa-info-circle text-primary me-2 mt-1"></i>
                        <div>
                            <small class="fw-semibold text-dark">安全说明</small>
                            <br>
                            <small class="text-muted">我们使用Google OAuth 2.0标准，不会存储您的Google密码，确保账户安全。</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 本地账户登录 -->
    <div class="col-lg-6 mb-4">
        <div class="feature-card h-100">
            <div class="card-body">
                <div class="text-center mb-4">
                    <div class="bg-gradient rounded-circle d-inline-flex align-items-center justify-content-center mb-3" style="width: 80px; height: 80px; background: var(--primary-gradient);">
                        <i class="fas fa-envelope fa-2x text-white"></i>
                    </div>
                    <h5 class="card-title fw-bold">邮箱账户登录</h5>
                    <p class="text-muted">使用您注册的邮箱地址和密码登录</p>
                </div>
                
                <!-- 登录表单 -->
                <div id="login-form">
                    <div class="mb-3">
                        <label class="form-label fw-semibold">
                            <i class="fas fa-envelope me-2 text-primary"></i>邮箱地址
                        </label>
                        <input type="email" class="form-control" id="login-email" placeholder="请输入您的邮箱地址">
                    </div>
                    <div class="mb-4">
                        <label class="form-label fw-semibold">
                            <i class="fas fa-lock me-2 text-primary"></i>登录密码
                        </label>
                        <input type="password" class="form-control" id="login-password" placeholder="请输入您的密码">
                    </div>
                    <div class="d-grid">
                        <button class="btn btn-primary btn-custom" onclick="login()">
                            <i class="fas fa-sign-in-alt me-2"></i>立即登录
                        </button>
                    </div>
                </div>
                
                <hr class="my-4">
                
                <div class="text-center">
                    <button class="btn btn-link text-decoration-none" onclick="toggleRegistration()">
                        <i class="fas fa-user-plus me-2"></i>还没有账户？立即注册
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 注册表单 -->
<div class="row mb-5 d-none" id="register-form-section">
    <div class="col-12">
        <div class="feature-card">
            <div class="card-body">
                <div class="text-center mb-4">
                    <div class="bg-gradient rounded-circle d-inline-flex align-items-center justify-content-center mb-3" style="width: 80px; height: 80px; background: var(--success-gradient);">
                        <i class="fas fa-user-plus fa-2x text-white"></i>
                    </div>
                    <h4 class="fw-bold">创建新账户</h4>
                    <p class="text-muted">填写下方信息完成账户注册</p>
                </div>
                
                <div class="row justify-content-center">
                    <div class="col-lg-8">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label fw-semibold">
                                        <i class="fas fa-user me-2 text-success"></i>用户名 
                                        <small class="text-muted">(可选)</small>
                                    </label>
                                    <input type="text" class="form-control" id="register-username" placeholder="请输入用户名">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label fw-semibold">
                                        <i class="fas fa-envelope me-2 text-success"></i>邮箱地址 
                                        <span class="text-danger">*</span>
                                    </label>
                                    <input type="email" class="form-control" id="register-email" placeholder="请输入邮箱地址" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label fw-semibold">
                                        <i class="fas fa-lock me-2 text-success"></i>登录密码 
                                        <span class="text-danger">*</span>
                                    </label>
                                    <input type="password" class="form-control" id="register-password" placeholder="至少6位字符" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label fw-semibold">
                                        <i class="fas fa-id-card me-2 text-success"></i>真实姓名 
                                        <small class="text-muted">(可选)</small>
                                    </label>
                                    <div class="row">
                                        <div class="col-6">
                                            <input type="text" class="form-control" id="register-firstname" placeholder="名字">
                                        </div>
                                        <div class="col-6">
                                            <input type="text" class="form-control" id="register-lastname" placeholder="姓氏">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mx-auto">
                                <div class="d-grid">
                                    <button class="btn btn-success btn-custom" onclick="register()">
                                        <i class="fas fa-user-check me-2"></i>创建账户
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="text-center mt-4">
                    <button class="btn btn-link text-decoration-none" onclick="toggleRegistration()">
                        <i class="fas fa-arrow-left me-2"></i>已有账户？返回登录
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 认证功能测试 -->
<div class="row mb-5 d-none" id="auth-tests">
    <div class="col-12">
        <div class="feature-card">
            <div class="card-body">
                <div class="d-flex align-items-center mb-4">
                    <div class="bg-gradient rounded-circle d-inline-flex align-items-center justify-content-center me-3" style="width: 60px; height: 60px; background: var(--warning-gradient);">
                        <i class="fas fa-flask text-white fa-xl"></i>
                    </div>
                    <div>
                        <h5 class="card-title mb-1 fw-bold">认证功能测试套件</h5>
                        <p class="text-muted mb-0">测试各种需要认证的API端点和功能</p>
                    </div>
                </div>
                
                <div class="row g-4 mb-4">
                    <div class="col-md-4">
                        <div class="d-grid">
                            <button class="btn btn-outline-primary btn-custom" onclick="testGetCurrentUser()">
                                <i class="fas fa-user me-2"></i>获取用户信息
                            </button>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="d-grid">
                            <button class="btn btn-outline-info btn-custom" onclick="testRefreshToken()">
                                <i class="fas fa-sync-alt me-2"></i>刷新认证令牌
                            </button>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="d-grid">
                            <button class="btn btn-outline-success btn-custom" onclick="testCreatePost()">
                                <i class="fas fa-edit me-2"></i>创建测试文章
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- 密码修改区域 -->
                <div class="bg-light rounded-4 p-4" id="change-password-section">
                    <h6 class="fw-bold mb-3">
                        <i class="fas fa-key me-2 text-warning"></i>修改登录密码
                    </h6>
                    <div class="row g-3">
                        <div class="col-md-4">
                            <label class="form-label fw-semibold small">当前密码</label>
                            <input type="password" class="form-control" id="old-password" placeholder="请输入当前密码">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-semibold small">新密码</label>
                            <input type="password" class="form-control" id="new-password" placeholder="请输入新密码">
                        </div>
                        <div class="col-md-4 d-flex align-items-end">
                            <div class="d-grid w-100">
                                <button class="btn btn-warning btn-custom" onclick="changePassword()">
                                    <i class="fas fa-save me-2"></i>修改密码
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 实时测试结果 -->
<div class="row">
    <div class="col-12">
        <div class="feature-card">
            <div class="card-body">
                <div class="d-flex align-items-center justify-content-between mb-4">
                    <div class="d-flex align-items-center">
                        <div class="bg-gradient rounded-circle d-inline-flex align-items-center justify-content-center me-3" style="width: 50px; height: 50px; background: linear-gradient(135deg, #1a202c, #2d3748);">
                            <i class="fas fa-terminal text-white"></i>
                        </div>
                        <div>
                            <h5 class="card-title mb-1 fw-bold">实时测试控制台</h5>
                            <p class="text-muted mb-0">查看认证测试的详细日志和响应信息</p>
                        </div>
                    </div>
                    <button class="btn btn-outline-secondary btn-custom" onclick="clearTestResults()">
                        <i class="fas fa-trash me-2"></i>清空日志
                    </button>
                </div>
                
                <div id="test-results" class="code-block" style="max-height: 400px; overflow-y: auto;">
                    <div class="d-flex align-items-center text-muted">
                        <div class="loading-spinner me-3" style="width: 1rem; height: 1rem; border-width: 2px;"></div>
                        <span>认证测试控制台已初始化，等待测试命令...</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// 全局变量
let accessToken = localStorage.getItem('access_token');
let refreshToken = localStorage.getItem('refresh_token');
let currentUser = null;

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    showResult('🚀 认证测试页面已加载完成');
    showResult('🔍 检查本地存储的认证信息...');
    
    // 检查现有token
    if (accessToken) {
        showResult('✅ 发现本地token，正在验证有效性...');
        getCurrentUser();
    } else {
        showResult('ℹ️ 未发现本地token，请先进行登录');
    }
    
    // 初始化Google登录
    initializeGoogleSignIn();
    
    // 获取后端认证配置
    checkAuthConfig();
});

// 初始化Google登录
function initializeGoogleSignIn() {
    showResult('🔧 正在初始化Google OAuth客户端...');
    
    // 确保DOM完全加载
    if (document.readyState !== 'complete') {
        setTimeout(initializeGoogleSignIn, 100);
        return;
    }
    
    // 确保Google SDK已加载
    if (typeof google === 'undefined' || !google.accounts || !google.accounts.id) {
        console.log('⏳ 等待Google SDK加载...');
        setTimeout(initializeGoogleSignIn, 200);
        return;
    }
    
    console.log('🔧 开始初始化Google OAuth...');
    
    fetch('/api/v1/auth/config')
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP错误: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('📋 后端配置响应:', data);
            
            if (data.success && data.data.googleEnabled && data.data.googleClientId) {
                console.log('✅ Google配置有效，开始初始化...');
                
                try {
                    // 初始化Google Identity Services
                    google.accounts.id.initialize({
                        client_id: data.data.googleClientId,
                        callback: handleGoogleSignIn,
                        auto_select: false,
                        cancel_on_tap_outside: true,
                        use_fedcm_for_prompt: false  // 禁用FedCM避免兼容性问题
                    });
                    
                    // 渲染登录按钮
                    const buttonContainer = document.getElementById('google-signin-button');
                    if (buttonContainer) {
                        google.accounts.id.renderButton(
                            buttonContainer,
                            { 
                                theme: 'outline', 
                                size: 'large', 
                                text: 'signin_with', 
                                shape: 'rectangular',
                                width: '250',
                                locale: 'zh-CN'
                            }
                        );
                        console.log('🎨 Google登录按钮已渲染');
                    }
                    
                    showResult('✅ Google OAuth配置加载成功');
                } catch (initError) {
                    console.error('Google初始化错误:', initError);
                    showResult('❌ Google初始化失败: ' + initError.message);
                }
            } else {
                console.warn('⚠️ Google OAuth未正确配置');
                showResult('⚠️ Google OAuth未配置或未启用');
                
                // 显示配置提示
                const buttonContainer = document.getElementById('google-signin-button');
                if (buttonContainer) {
                    buttonContainer.innerHTML = 
                        '<div class="alert alert-warning mb-0"><small><i class="fas fa-exclamation-triangle me-2"></i>Google OAuth 未配置</small></div>';
                }
            }
        })
        .catch(error => {
            console.error('获取Google配置失败:', error);
            showResult('❌ 获取Google配置失败: ' + error.message);
            
            // 显示错误信息
            const buttonContainer = document.getElementById('google-signin-button');
            if (buttonContainer) {
                buttonContainer.innerHTML = 
                    '<div class="alert alert-danger mb-0"><small><i class="fas fa-times-circle me-2"></i>无法连接到后端服务器</small></div>';
            }
        });
}

// 处理Google登录 - 改进错误处理和响应处理
async function handleGoogleSignIn(response) {
    console.log('🔔 收到Google登录回调:', response);
    
    try {
        // 验证响应格式
        if (!response || !response.credential) {
            throw new Error('Google响应格式无效：缺少credential');
        }
        
        showResult('🔄 正在处理Google登录凭据...');
        
        console.log('📤 发送登录请求到后端...');
        const result = await fetch('/api/v1/auth/google', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ credential: response.credential })
        });
        
        console.log('📥 后端响应状态:', result.status);
        
        if (!result.ok) {
            const errorText = await result.text();
            throw new Error(`HTTP错误 ${result.status}: ${errorText}`);
        }
        
        const data = await result.json();
        console.log('📋 后端响应数据:', data);
        
        if (data.success) {
            accessToken = data.data.token;
            refreshToken = data.data.refreshToken;
            currentUser = data.data.user;
            
            localStorage.setItem('access_token', accessToken);
            if (refreshToken) {
                localStorage.setItem('refresh_token', refreshToken);
            }
            
            console.log('✅ 登录数据已保存到本地存储');
            
            updateAuthStatus(true);
            showResult(`🎉 Google登录成功！欢迎 ${currentUser.firstName || currentUser.email}`);
            
            // 自动滚动到认证状态区域
            document.getElementById('user-info')?.scrollIntoView({ behavior: 'smooth' });
        } else {
            throw new Error(data.message || '登录失败，未知原因');
        }
    } catch (error) {
        console.error('💥 Google登录处理错误:', error);
        showResult(`❌ Google登录失败: ${error.message}`);
        
        // 额外的调试信息
        if (error.name === 'TypeError' && error.message.includes('fetch')) {
            showResult('🔍 提示：请确保后端服务器运行在正确端口且认证路由已配置');
        }
    }
}

// 本地登录
async function login() {
    const email = document.getElementById('login-email').value;
    const password = document.getElementById('login-password').value;
    
    if (!email || !password) {
        showResult('❌ 邮箱和密码为必填项');
        return;
    }
    
    try {
        showResult('🔐 正在验证登录凭据...');
        
        const response = await fetch('/api/v1/auth/login', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ email, password })
        });
        
        const data = await response.json();
        
        if (data.success) {
            accessToken = data.data.token;
            refreshToken = data.data.refreshToken;
            currentUser = data.data.user;
            
            localStorage.setItem('access_token', accessToken);
            if (refreshToken) {
                localStorage.setItem('refresh_token', refreshToken);
            }
            
            updateAuthStatus(true);
            showResult(`🎉 登录成功！欢迎回来 ${currentUser.email}`);
            
            // 清空密码框（安全起见）
            document.getElementById('login-password').value = '';
        } else {
            showResult(`❌ 登录失败: ${data.message}`);
        }
    } catch (error) {
        showResult(`💥 登录请求出错: ${error.message}`);
    }
}

// 用户注册
async function register() {
    const username = document.getElementById('register-username').value;
    const email = document.getElementById('register-email').value;
    const password = document.getElementById('register-password').value;
    const firstName = document.getElementById('register-firstname').value;
    const lastName = document.getElementById('register-lastname').value;
    
    if (!email || !password) {
        showResult('❌ 邮箱和密码为必填项');
        return;
    }
    
    if (password.length < 6) {
        showResult('❌ 密码长度至少为6位');
        return;
    }
    
    try {
        showResult('📝 正在创建新用户账户...');
        
        const response = await fetch('/api/v1/auth/register', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                username: username || undefined,
                email,
                password,
                firstName: firstName || undefined,
                lastName: lastName || undefined,
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            accessToken = data.data.token;
            refreshToken = data.data.refreshToken;
            currentUser = data.data.user;
            
            localStorage.setItem('access_token', accessToken);
            if (refreshToken) {
                localStorage.setItem('refresh_token', refreshToken);
            }
            
            updateAuthStatus(true);
            showResult(`🎉 注册成功！欢迎加入 ${currentUser.email}`);
            
            // 隐藏注册表单
            document.getElementById('register-form-section').classList.add('d-none');
            clearRegisterForm();
        } else {
            showResult(`❌ 注册失败: ${data.message}`);
        }
    } catch (error) {
        showResult(`💥 注册请求出错: ${error.message}`);
    }
}

// 获取当前用户信息
async function getCurrentUser() {
    if (!accessToken) {
        showResult('❌ 缺少访问令牌，请先登录');
        return;
    }
    
    try {
        showResult('👤 正在获取当前用户信息...');
        
        const response = await fetch('/api/v1/auth/me', {
            headers: { 'Authorization': `Bearer ${accessToken}` }
        });
        
        const data = await response.json();
        
        if (data.success) {
            currentUser = data.data;
            updateAuthStatus(true);
            showResult('✅ 用户信息获取成功');
        } else {
            if (response.status === 401) {
                showResult('🔄 令牌已过期，尝试自动刷新...');
                await attemptTokenRefresh();
            } else {
                showResult(`❌ 获取用户信息失败: ${data.message}`);
            }
        }
    } catch (error) {
        showResult(`💥 获取用户信息出错: ${error.message}`);
    }
}

// 安全登出
function logout() {
    showResult('👋 正在安全登出...');
    
    accessToken = null;
    refreshToken = null;
    currentUser = null;
    
    localStorage.removeItem('access_token');
    localStorage.removeItem('refresh_token');
    
    updateAuthStatus(false);
    showResult('✅ 已安全登出，所有本地认证信息已清除');
}

// 更新认证状态显示
function updateAuthStatus(isAuthenticated) {
    const statusEl = document.getElementById('auth-status');
    const userInfoEl = document.getElementById('user-info');
    const loginFormsEl = document.getElementById('login-forms');
    const authTestsEl = document.getElementById('auth-tests');
    
    if (isAuthenticated) {
        statusEl.className = 'status-badge status-running';
        statusEl.innerHTML = '<i class="fas fa-check-circle me-2"></i>已认证';
        
        userInfoEl.classList.remove('d-none');
        loginFormsEl.classList.add('d-none');
        authTestsEl.classList.remove('d-none');
        
        showUserDetails();
    } else {
        statusEl.className = 'status-badge status-stopped';
        statusEl.innerHTML = '<i class="fas fa-times-circle me-2"></i>未登录';
        
        userInfoEl.classList.add('d-none');
        loginFormsEl.classList.remove('d-none');
        authTestsEl.classList.add('d-none');
    }
}

// 显示用户详细信息
function showUserDetails() {
    if (!currentUser) return;
    
    const detailsEl = document.getElementById('user-details');
    detailsEl.innerHTML = `
        <div class="row g-3">
            <div class="col-md-6">
                <div class="d-flex align-items-center">
                    <i class="fas fa-id-badge text-primary me-2"></i>
                    <div>
                        <small class="text-muted">用户ID</small>
                        <div class="fw-semibold">${currentUser.id}</div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="d-flex align-items-center">
                    <i class="fas fa-envelope text-primary me-2"></i>
                    <div>
                        <small class="text-muted">邮箱地址</small>
                        <div class="fw-semibold">${currentUser.email}</div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="d-flex align-items-center">
                    <i class="fas fa-user text-primary me-2"></i>
                    <div>
                        <small class="text-muted">用户名</small>
                        <div class="fw-semibold">${currentUser.username || '未设置'}</div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="d-flex align-items-center">
                    <i class="fas fa-id-card text-primary me-2"></i>
                    <div>
                        <small class="text-muted">姓名</small>
                        <div class="fw-semibold">${(currentUser.firstName || '') + ' ' + (currentUser.lastName || '') || '未设置'}</div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="d-flex align-items-center">
                    <i class="fas fa-shield-alt text-primary me-2"></i>
                    <div>
                        <small class="text-muted">认证方式</small>
                        <div class="fw-semibold">${currentUser.provider}</div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="d-flex align-items-center">
                    <i class="fas fa-toggle-${currentUser.isActive ? 'on text-success' : 'off text-danger'} me-2"></i>
                    <div>
                        <small class="text-muted">账户状态</small>
                        <div class="fw-semibold">${currentUser.isActive ? '已激活' : '已禁用'}</div>
                    </div>
                </div>
            </div>
        </div>
    `;
}

// 切换注册/登录表单
function toggleRegistration() {
    const registerSection = document.getElementById('register-form-section');
    registerSection.classList.toggle('d-none');
    
    if (!registerSection.classList.contains('d-none')) {
        showResult('📝 切换到注册模式');
    } else {
        showResult('🔐 切换到登录模式');
        clearRegisterForm();
    }
}

// 清空注册表单
function clearRegisterForm() {
    ['register-username', 'register-email', 'register-password', 'register-firstname', 'register-lastname'].forEach(id => {
        document.getElementById(id).value = '';
    });
}

// 显示测试结果
function showResult(message) {
    const resultEl = document.getElementById('test-results');
    const timestamp = new Date().toLocaleTimeString('zh-CN');
    const logLine = `[${timestamp}] ${message}`;
    
    if (resultEl.innerHTML.includes('等待测试命令')) {
        resultEl.innerHTML = logLine;
    } else {
        resultEl.innerHTML += '\n' + logLine;
    }
    
    resultEl.scrollTop = resultEl.scrollHeight;
}

// 清空测试结果
function clearTestResults() {
    const resultEl = document.getElementById('test-results');
    resultEl.innerHTML = '<div class="text-muted">📝 测试控制台已清空，等待新的测试命令...</div>';
    showResult('🧹 测试日志已清空');
}

// 检查认证配置
async function checkAuthConfig() {
    try {
        showResult('⚙️ 正在检查后端认证配置...');
        
        const response = await fetch('/api/v1/auth/config');
        const data = await response.json();
        
        if (data.success) {
            showResult(`✅ 认证配置检查完成 - Google OAuth: ${data.data.googleEnabled ? '已启用' : '未启用'}`);
        } else {
            showResult(`⚠️ 认证配置检查异常: ${data.message}`);
        }
    } catch (error) {
        showResult(`💥 检查认证配置出错: ${error.message}`);
    }
}

// 测试功能函数
async function testGetCurrentUser() {
    showResult('🧪 开始测试：获取当前用户信息');
    await getCurrentUser();
}

async function testRefreshToken() {
    if (!refreshToken) {
        showResult('❌ 测试失败：缺少刷新令牌');
        return;
    }
    
    try {
        showResult('🧪 开始测试：刷新访问令牌');
        
        const response = await fetch('/api/v1/auth/refresh', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ refreshToken })
        });
        
        const data = await response.json();
        
        if (data.success) {
            accessToken = data.data.token;
            refreshToken = data.data.refreshToken;
            
            localStorage.setItem('access_token', accessToken);
            localStorage.setItem('refresh_token', refreshToken);
            
            showResult('✅ 令牌刷新测试成功');
        } else {
            showResult(`❌ 令牌刷新测试失败: ${data.message}`);
        }
    } catch (error) {
        showResult(`💥 令牌刷新测试出错: ${error.message}`);
    }
}

async function testCreatePost() {
    if (!accessToken) {
        showResult('❌ 测试失败：需要先登录获取访问令牌');
        return;
    }
    
    try {
        showResult('🧪 开始测试：创建测试文章');
        
        const response = await fetch('/api/v1/posts', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${accessToken}`
            },
            body: JSON.stringify({
                title: '认证测试文章 - ' + new Date().toLocaleString('zh-CN'),
                content: '这是一篇通过认证测试页面创建的测试文章，用于验证API的认证功能是否正常工作。',
                summary: '认证功能测试',
                authorId: currentUser?.id
            })
        });
        
        const data = await response.json();
        
        if (data.success || response.status === 201) {
            showResult('✅ 文章创建测试成功');
        } else {
            showResult(`❌ 文章创建测试失败: ${data.message}`);
        }
    } catch (error) {
        showResult(`💥 文章创建测试出错: ${error.message}`);
    }
}

async function changePassword() {
    const oldPassword = document.getElementById('old-password').value;
    const newPassword = document.getElementById('new-password').value;
    
    if (!oldPassword || !newPassword) {
        showResult('❌ 请输入当前密码和新密码');
        return;
    }
    
    if (newPassword.length < 6) {
        showResult('❌ 新密码长度至少为6位');
        return;
    }
    
    try {
        showResult('🧪 开始测试：修改用户密码');
        
        const response = await fetch('/api/v1/auth/change-password', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${accessToken}`
            },
            body: JSON.stringify({ oldPassword, newPassword })
        });
        
        const data = await response.json();
        
        if (data.success) {
            showResult('✅ 密码修改测试成功');
            // 清空密码框
            document.getElementById('old-password').value = '';
            document.getElementById('new-password').value = '';
        } else {
            showResult(`❌ 密码修改测试失败: ${data.message}`);
        }
    } catch (error) {
        showResult(`💥 密码修改测试出错: ${error.message}`);
    }
}

// 尝试自动刷新令牌
async function attemptTokenRefresh() {
    if (refreshToken) {
        await testRefreshToken();
        if (accessToken) {
            await getCurrentUser();
        }
    } else {
        showResult('❌ 无法自动刷新：缺少刷新令牌，请重新登录');
        logout();
    }
}
</script> 